﻿using System;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace Tools
{
    /// <summary>
    /// 创建WebClient.UploadData方法所需二进制数组,只使用于POST方法提交
    /// </summary>
    public class HttpPostHelper
    {
        /*
    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="__EVENTTARGET"


    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="__EVENTARGUMENT"


    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="__VIEWSTATE"

    /wEPDwUKLTk5NjY2ODc3NQ9kFgICAw8WAh4HZW5jdHlwZQUTbXVsdGlwYXJ0L2Zvcm0tZGF0YWRkof0Cj/2Kmm2CV38U9yqPY2Ae6bQ=
    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="File1"; filename="D:\项目\test.txt"
    Content-Type: text/plain

    this is a test!
    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="Submit1"
 
    submit
    -----------------------------7d81773bb037c
    Content-Disposition: form-data; name="__EVENTVALIDATION"

    /wEWAgKX9P2MDQLVo8avDo+7GACAh3TtgJ3FkBDx2akzGKil
    -----------------------------7d81773bb037c--

     */
        static string _code = "---------------------------7d5b915500cee";

        /// <summary>
        /// 
        /// </summary>
        public static string Boundary = "--" + _code;//前面多2个“--”
        
        /// <summary>
        /// ContentType
        /// </summary>
        public static string ContentType = "multipart/form-data; boundary=" + _code;//可以自己可以设置的，这里用统一的

        private List<byte> _byteList = new List<byte>();//动态数组
        private NameValueCollection _headers = new NameValueCollection();
        private Encoding _encoding = Encoding.UTF8;

        /// <summary>
        /// 拼接所有的二进制数组为一个数组
        /// </summary>
        /// <returns></returns>
        /// <remarks>加上结束边界</remarks>
        private byte[] JoinBytes()
        {
            int len = _byteList.Count;

            // 加上结束边界
            byte[] end_boundary_bytes = _encoding.GetBytes(Boundary + "--\r\n");//结束边界

            byte[] bytes = new byte[len + end_boundary_bytes.Length];//总长度

            //拷贝
            _byteList.CopyTo(bytes, 0);
            end_boundary_bytes.CopyTo(bytes, len);

            end_boundary_bytes = null;

            return bytes;
        }

        /// <summary>
        /// 2010-12-15 增加 by 杜有发，得到要上传的数据流
        /// </summary>
        public byte[] Data 
        {
            get { return JoinBytes(); }
        }

        /// <summary>
        /// 往指定的URL里发送数据
        /// </summary>
        /// <param name="uploadUrl">要发送数据的URL</param>
        /// <returns></returns>
        public byte[] UploadData(string uploadUrl)
        {
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", ContentType);

            byte[] bytes = JoinBytes();
            byte[] responseBytes;
            try
            {
                //追加headers
                int iCount = _headers.Count;
                string key;
                string value;
                for (int i = 0; i < iCount; i++)
                {
                    key = _headers.Keys[i];
                    value = _headers[i];
                    webClient.Headers.Add(key, value);
                }

                responseBytes = webClient.UploadData(uploadUrl, "Post", bytes);
                webClient.Dispose();//释放资源
                return responseBytes;
            }
            catch (WebException ex)
            {
                //Stream resp = ex.Response.GetResponseStream();
                //responseBytes = new byte[ex.Response.ContentLength];
                //resp.Read(responseBytes, 0, responseBytes.Length);

                responseBytes = _encoding.GetBytes(ex.ToString());
                webClient.Dispose();//释放资源
            }

            bytes = null;
            return responseBytes;
        }

        /// <summary>
        /// 获取普通表单区域二进制数组
        /// </summary>
        /// <param name="fieldName">表单名</param>
        /// <param name="fieldValue">表单值</param>
        /// <returns></returns>
        /// <remarks>
        /// -----------------------------7d52ee27210a3c\r\nContent-Disposition: form-data; name=\"表单名\"\r\n\r\n表单值\r\n
        /// </remarks>
        public HttpPostHelper AddData(string fieldName, string fieldValue)
        {
            string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";//最后的是换行
            string text = String.Format(textTemplate, fieldName, fieldValue);
            byte[] bytes = _encoding.GetBytes(text);
            _byteList.AddRange(bytes);
            return this;
        }

        /// <summary>
        /// 获取文件上传表单区域二进制数组
        /// </summary>
        /// <param name="fieldName">表单名</param>
        /// <param name="filename">文件名</param>
        /// <param name="contentType">文件类型</param>
        /// <param name="fileBytes">文件流</param>
        /// <returns></returns>
        public HttpPostHelper AddData(string fieldName, string filename, string contentType, byte[] fileBytes)
        {
            string end = "\r\n";
            string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";

            // 头数据
            string data = String.Format(textTemplate, fieldName, filename, contentType);
            byte[] bytes = _encoding.GetBytes(data);

            // 尾数据
            byte[] endBytes = _encoding.GetBytes(end);

            // 合成后的数组
            byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];

            bytes.CopyTo(fieldData, 0); // 头数据
            fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据
            endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // \r\n

            _byteList.AddRange(fieldData);
            return this;
        }

        #region 属性

        /// <summary>
        /// 字节编码，默认UTF-8
        /// </summary>
        public Encoding Encoding
        {
            get { return _encoding; }
            set { _encoding = value; }
        }

        /// <summary>
        /// 可以随意增加header，不受属性限制，不像httpwebrequest那样有些属性是要特殊设置的，比如content-length
        /// </summary>
        public NameValueCollection Headers
        {
            get { return _headers; }
            set { _headers = value; }
        }

        #endregion

        /*/// <summary>
        /// 来源 http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
        /// </summary>
        /// <param name="url"></param>
        /// <param name="files"></param>
        /// <param name="nvc"></param>
        /// <returns></returns>
        public static byte[] UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection nvc)
        {
            string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
            Encoding encoding = Encoding.UTF8;

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Credentials = CredentialCache.DefaultCredentials;

            Stream memStream = new MemoryStream();
            byte[] boundarybytes = encoding.GetBytes("\r\n--" + boundary + "\r\n");
            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = encoding.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }
            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n"; 
            for (int i = 0; i < files.Length; i++)
            {     
                string header = string.Format(headerTemplate, "uplTheFile", files[i]);//name的值，值得商榷 2010-12-15
                byte[] headerbytes = encoding.GetBytes(header); 
                memStream.Write(headerbytes, 0, headerbytes.Length);

                FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read); 
                byte[] buffer = new byte[1024]; 
                int bytesRead = 0; 
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) 
                { 
                    memStream.Write(buffer, 0, bytesRead);
                } 
                memStream.Write(boundarybytes, 0, boundarybytes.Length); 
                fileStream.Close();
            } 
            httpWebRequest.ContentLength = memStream.Length; 

            //输入流
            Stream requestStream = httpWebRequest.GetRequestStream(); 
            memStream.Position = 0;
 
            byte[] tempBuffer = new byte[memStream.Length]; 
            memStream.Read(tempBuffer, 0, tempBuffer.Length); 
            memStream.Close();
            memStream.Dispose();

            requestStream.Write(tempBuffer, 0, tempBuffer.Length); 
            requestStream.Close(); 

            //响应
            byte[] rtn;
            try
            {
                WebResponse webResponse = httpWebRequest.GetResponse();
                Stream stream = webResponse.GetResponseStream();
                int len = (int)stream.Length;
                rtn = new byte[len];
                stream.Write(rtn, 0, len);
                webResponse.Close();
                httpWebRequest = null;
                webResponse = null;
            }
            catch (Exception ex)
            {
                rtn = Encoding.UTF8.GetBytes(ex.ToString());
            }

            return rtn;
        }*/
    }
}
